package com.example.cloud.controller.personal;

import com.example.cloud.constants.CommonConstants;
import com.example.cloud.controller.common.BaseController;
import com.example.cloud.model.dto.QueryModel;
import com.example.cloud.model.dto.Result;
import com.example.cloud.model.personal.AttendanceRecord;
import com.example.cloud.model.system.Organ;
import com.example.cloud.model.system.User;
import com.example.cloud.service.personal.AttendanceService;
import com.example.cloud.utils.RequestUtil;
import com.example.cloud.utils.ResultUtil;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by wangtao on 2018/5/22.
 */
@RestController
@RequestMapping("/attendance")
public class AttendanceController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(AttendanceController.class);

    @Autowired
    private AttendanceService attendanceService;

    @PostMapping("/search")
    public Result search(@RequestBody QueryModel model) {
        return this.singleQuery(model, AttendanceRecord.class);
    }

    @RequestMapping("/getCalendar/{month}/{userId}")
    public Result getCalendar(@PathVariable String month, @PathVariable Long userId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        List<List<AttendanceRecord>> resultList = null;
        try {
            resultList = attendanceService.findAllByCurrentDate(sdf.parse(month), RequestUtil.getLoginUser(), userId);
        } catch (Exception e) {
            logger.error("查询作息表异常：" + e.getMessage(), e);
            ResultUtil.fail("系统异常，请联系管理员");
        }
        return ResultUtil.success(resultList);
    }

    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody AttendanceRecord record) throws ParseException {
        return attendanceService.doSave(record);
    }

    @PostMapping("/relaxation")
    public void relaxation(@RequestBody AttendanceRecord record) throws ParseException {
        record.setStartTime(DateUtils.parseDate(record.getStartTimeStr(), CommonConstants.DATE_FORMATS));
        record.setEndTime(DateUtils.parseDate(record.getEndTimeStr(), CommonConstants.DATE_FORMATS));
        attendanceService.doRelaxation(record);
    }

    @PostMapping("/checkAgree")
    public Result checkAgree(@RequestBody List<Long> ids) {
        return ResultUtil.success(attendanceService.checkAgree(ids));
    }

    @PostMapping("/agree")
    public void agree(@RequestBody List<Long> ids) {
        List canList = attendanceService.checkAgree(ids);
        if (canList.size() > 0) {
            attendanceService.doAgree(canList);
        }
    }

    @GetMapping("/checkRefuse/{id}")
    public Result checkRefuse(@PathVariable Long id) {
        return ResultUtil.success(attendanceService.checkRefuse(id));
    }

    @PostMapping("/refuse")
    public void refuse(@RequestBody Map params) {
        Long id = Long.valueOf(String.valueOf(params.get("id")));
        String denialReason = String.valueOf(params.get("denialReason"));
        boolean check = attendanceService.checkRefuse(id);
        if (check) {
            attendanceService.doRefuse(id, denialReason);
        }
    }

    @GetMapping("/getHealthcare/{datetime}")
    public Result getHealthcare(@PathVariable String datetime) {
        Result result = new Result();
        result.setCode(CommonConstants.SUCCESS);
        result.setMsg("操作成功");
        List<User> users = new ArrayList<>();
        try {
            User user = RequestUtil.getLoginUser();
            List<Organ> organs = user.getOrgans();
            if (organs.isEmpty()) {
                result.setCode(CommonConstants.FAILURE);
                result.setMsg("该用户没有任何织机构权限");
                return result;
            }
            List<Long> organIds = new ArrayList<>();
            for (Organ organ : organs) {
                organIds.add(organ.getId());
            }
            users = attendanceService.getHealthcare(organIds, datetime);
            result.setData(users);
        } catch (Exception e) {
            logger.error("预约查询医护异常：" + e.getMessage(), e);
            result.setCode(CommonConstants.FAILURE);
            result.setMsg("查询异常");
        }
        return result;
    }

    @PostMapping("/delete")
    public void delete(@RequestBody List<Long> ids){
        attendanceService.doDelete(ids);
    }
}
